<?php

use Drupal\ssy_live_room\Entity\SsyLiveRoom;

function ssy_live_room_ssy_live_room_entity_form($form, &$form_state, SsyLiveRoom $e, $op) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'ssy_live_room') . '/ssy_live_room.forms.inc';
  $form_state[SsyLiveRoom::class] = $e;


  $form['name'] = [
    '#type' => 'textfield',
    '#title' => t('直播间名字'),
    '#required' => TRUE,
    '#default_value' => $e->name,
    '#element_validate' => ['ssy_live_room_validate_name_length'],
    '#description' => t('直播间名字，最短3个汉字，最长17个汉字'),
  ];
  $form['start_time'] = [
    '#title' => t('直播计划开始时间'),
    '#required' => TRUE,
    '#type' => 'date_popup',
    '#date_format' => 'Y-m-d H:i:s',
    '#date_label_position' => 'within',
    '#date_year_range' => '-1:+1',
    '#default_value' => format_date($e->start_time, 'custom', 'Y-m-d H:i:s'),
    '#description' => t('直播计划开始时间（开播时间需要在当前时间的10分钟后 并且 开始时间不能在 6 个月后）'),
  ];
  $form['end_time'] = [
    '#required' => TRUE,
    '#type' => 'date_popup',
    '#date_format' => 'Y-m-d H:i:s',
    '#date_label_position' => 'within',
    '#date_year_range' => '-1:+1',
    '#default_value' => format_date($e->end_time, 'custom', 'Y-m-d H:i:s'),
    '#description' => t('直播计划结束时间（开播时间和结束时间间隔不得短于30分钟，不得超过24小时）'),
  ];
  $form['anchor_name'] = [
    '#type' => 'textfield',
    '#title' => t('主播昵称'),
    '#required' => TRUE,
    '#default_value' => $e->anchor_name,
    '#element_validate' => ['ssy_live_room_validate_anchor_name_length'],
    '#description' => t('主播昵称，最短2个汉字，最长15个汉字'),
  ];
  $form['anchor_wechat'] = [
    '#type' => 'textfield',
    '#title' => t('主播微信号'),
    '#required' => TRUE,
    '#default_value' => $e->anchor_wechat,
    '#description' => t('主播微信号，如果未实名认证，需要先前往“小程序直播”小程序进行实名验证, 小程序二维码链接：<a href="@link">@link</a>', ['@link' => 'https://res.wx.qq.com/op_res/9rSix1dhHfK4rR049JL0PHJ7TpOvkuZ3mE0z7Ou_Etvjf-w1J_jVX0rZqeStLfwh']),
  ];

  field_attach_form($e->entityType(), $e, $form, $form_state);

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];
  $form['actions']['preview'] = [
    '#type' => 'submit',
    '#value' => t('保存并审核'),
    '#submit' => ['ssy_live_room_ssy_live_room_entity_form_submit_audit'],
  ];
  return $form;
}

function ssy_live_room_validate_name_length($element, &$form_state) {
  $value = $element['#value'];
  if (mb_strlen($value) > 17) {
    form_error($element, t('%name 不能超过 17 个汉字.', ['%name' => $element['#title']]));
  }
}

function ssy_live_room_validate_anchor_name_length($element, &$form_state) {
  $value = $element['#value'];
  if (mb_strlen($value) > 15) {
    form_error($element, t('%name 不能超过 15 个汉字.', ['%name' => $element['#title']]));
  }
}

function ssy_live_room_ssy_live_room_entity_form_validate($form, &$form_state) {
  $e = $form_state[SsyLiveRoom::class];
  if ($e instanceof SsyLiveRoom) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->start_time = strtotime($e->start_time);
    $e->end_time = strtotime($e->end_time);
    if ($e->start_time <= REQUEST_TIME + (10 * 60) || $e->start_time > REQUEST_TIME + (6 * 30 * 24 * 60 * 60)) {
      form_error($form['start_time'], '开播时间需要在当前时间的10分钟后 不能超过6个月后');
    }
    if ($e->end_time - $e->start_time < (30 * 60) || $e->end_time - $e->start_time > (24 * 60 * 60)) {
      form_error($form['end_time'], '开播时间和结束时间间隔不得短于30分钟,不得超过24小时');
    }
  }
}

function ssy_live_room_ssy_live_room_entity_form_submit($form, &$form_state) {
  $e = $form_state[SsyLiveRoom::class];
  if ($e instanceof SsyLiveRoom) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->start_time = strtotime($e->start_time);
    $e->end_time = strtotime($e->end_time);
    $e->save();
  }
}

function ssy_live_room_ssy_live_room_entity_form_submit_audit($form, &$form_state) {
  $e = $form_state[SsyLiveRoom::class];
  if ($e instanceof SsyLiveRoom) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->start_time = strtotime($e->start_time);
    $e->end_time = strtotime($e->end_time);
    $e->save();
    //重新LOAD 才能读取 field 图片
    $e = ssy_live_room_load($e->id);
    $ew = $e->wrapper();
    $field_coverimg = $ew->field_coverimg->value();
    $field_shareimg = $ew->field_shareimg->value();
    $field_feedsimg = $ew->field_feedsimg->value();
    $app = wx_mini_program_get_app();
    $coverimg = $app->media->uploadImage($field_coverimg['uri']);
    $shareImg = $app->media->uploadImage($field_shareimg['uri']);
    $feedsImg = $app->media->uploadImage($field_feedsimg['uri']);
    $room = [
      "name" => $e->name,
      // 房间名字
      "coverImg" => $coverimg['media_id'],
      // 通过 uploadfile 上传，填写 mediaID
      "startTime" => $e->start_time,
      // 开始时间
      "endTime" => $e->end_time,
      // 结束时间
      "anchorName" => $e->anchor_name,
      // 主播昵称
      "anchorWechat" => $e->anchor_wechat,
      // 主播微信号
      "subAnchorWechat" => $e->sub_anchor_wechat,
      // 主播副号微信号
      "createrWechat" => $e->creater_wechat,
      // 创建者微信号
      "shareImg" => $shareImg['media_id'],
      //通过 uploadfile 上传，填写 mediaID
      "feedsImg" => $feedsImg['media_id'],
      //通过 uploadfile 上传，填写 mediaID
      "isFeedsPublic" => $e->is_feeds_public,
      // 是否开启官方收录，1 开启，0 关闭
      "type" => $e->type,
      // 直播类型，1 推流 0 手机直播
      "closeLike" => $e->close_like,
      // 是否关闭点赞 1：关闭
      "closeGoods" => $e->close_goods,
      // 是否关闭商品货架，1：关闭
      "closeComment" => $e->close_comment,
      // 是否开启评论，1：关闭
      "closeReplay" => $e->close_replay,
      // 是否关闭回放 1 关闭
      "closeShare" => $e->close_share,
      //  是否关闭分享 1 关闭
      "closeKf" => $e->close_kf,
      // 是否关闭客服，1 关闭
    ];
    $result = $app->broadcast->createLiveRoom($room);
    if ($result['errcode'] == 0) {
      $e->room_id = $result['roomId'];
      $e->save();
      drupal_set_message('直播间创建成功.');
    }
    else {
      //errmsg (String, 64 characters ) parameter name length is invalid rid: 61f26a33-...
      //errcode (Integer) 300002
      drupal_set_message($result['errcode'] . '--' . $result['errmsg'], 'error');
    }
    //    dpm($result);
  }
}

function ssy_live_room_ssy_live_room_delete_form($form, &$form_state, SsyLiveRoom $e) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'ssy_live_room') . '/ssy_live_room.forms.inc';
  $form_state[SsyLiveRoom::class] = $e;
  return confirm_form($form, t('Are you sure you want to delete %title?', ['%title' => $e->label()]), 'admin/content/ssy_live_room/' . $e->id, t('This action cannot be undone.'), t('Delete'), t('Cancel'));
}

function ssy_live_room_ssy_live_room_delete_form_submit($form, &$form_state) {
  $e = $form_state[SsyLiveRoom::class];
  if ($e instanceof SsyLiveRoom) {
    $e->delete();
  }
  $form_state['redirect'] = 'admin/content/ssy_live_room';
}

